package com.star.robot.controller;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.star.robot.dto.*;
import com.star.robot.enums.AdminTypeEnum;
import com.star.robot.repository.*;
import com.star.robot.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.star.robot.constant.Constant;
import com.star.robot.entity.Admin;
import com.star.robot.util.DtAreaUtil;

import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "/admin")
public class AdminController {

    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private DtAreaUtil dtAreaUtil;

    @Autowired
    private AdminService adminService;
    
    @ApiOperation(value = "管理员登录",notes="管理员登录")
    @PostMapping(value = "/login")
    public ResultDto login(@RequestBody AdminLoginDto requestDto , HttpServletRequest request){
        validLoginParam(requestDto);
        Admin admin = adminRepository.findByUsernameAndPasswd(requestDto.getUsername() , requestDto.getPasswd());
        if(admin != null){
            //session绑定手机号
            request.getSession().setAttribute(Constant.CURRENTADMIN, admin);
            return ResultDto.builder().build();
        }else{
            return ResultDto.builder().success(Boolean.FALSE).build();
        }

    }

    private void validLoginParam(AdminLoginDto requestDto) {
        //用户名必填
        if(StringUtils.isEmpty(requestDto.getUsername())){
            throw new IllegalArgumentException("用户名");
        }
        //密码必填
        if(StringUtils.isEmpty(requestDto.getPasswd())){
            throw new IllegalArgumentException("密码必填");
        }
    }

    @ApiOperation(value = "管理员新增",notes="管理员新增")
    @PostMapping(value = "/")
    public ResultDto add(@RequestBody Admin requestDto , HttpServletRequest request){
//        validAddParam(requestDto);
        requestDto.setSuperAdmin(Boolean.FALSE);
        adminRepository.save((Admin)requestDto);
        return ResultDto.builder().success(Boolean.TRUE).build();

    }

    @ApiOperation(value = "管理员修改密码",notes="管理员修改密码")
    @PostMapping(value = "/modifyPwd")
    public ResultDto modifyPwd(String passwd, String newPasswd , HttpServletRequest request){

        //
        if(StringUtils.isEmpty(passwd)){
            throw new IllegalArgumentException("密码必填");
        }
        //密码必填
        if(StringUtils.isEmpty(newPasswd)){
            throw new IllegalArgumentException("新密码必填");
        }

        Admin currentAdmin = adminService.getCurrentAdmin(request);


        Admin adminQuery = adminRepository.findByUsernameAndPasswd(currentAdmin.getUsername(), passwd);

        if (adminQuery == null) {
            return ResultDto.builder().success(Boolean.FALSE).message("密码错误").build();
        }

        adminQuery.setPasswd(newPasswd);

        adminRepository.save(adminQuery);

        return ResultDto.builder().success(Boolean.TRUE).build();

    }

    private void validAddParam(AdminLoginDto requestDto) {
//        //用户名必填
//        if(StringUtils.isEmpty(requestDto.getUsername())){
//            throw new IllegalArgumentException("用户名");
//        }
//        //密码必填
//        if(StringUtils.isEmpty(requestDto.getPasswd())){
//            throw new IllegalArgumentException("密码必填");
//        }
    }
    @ApiOperation(value = "管理员查询",notes="管理员查询")
    @GetMapping(value = "/query")
    private PageResultDto query(AdminQueryDto requestDto){
        PageResultDto<Admin> results = new PageResultDto<>();
        if(requestDto.getPage() != null && requestDto.getLimit() != null) {
            //后端框架分页从0开始 前端框架从1开始
            if (requestDto.getPage() >= 1) {
                requestDto.setPage(requestDto.getPage() - 1);
            }
            Pageable page = new PageRequest(requestDto.getPage(), requestDto.getLimit());

            Page<Admin> pagedAdmin = adminRepository.findAll(new Specification<Admin>() {
                @Override
                public Predicate toPredicate(Root<Admin> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {

                    //总条件
                    List<Predicate> conditions = new ArrayList<>();

                    //省
                    if(requestDto.getProvinceId() != null){
                        //所在地区
                        Predicate provinceCond = cb.equal(root.get("provinceId") ,requestDto.getProvinceId());
                        conditions.add(provinceCond);
                    }
                    //市
                    if(requestDto.getCityId() != null){
                        Predicate areaCondition = cb.equal(root.get("cityId") ,requestDto.getCityId());
                        conditions.add(areaCondition);
                    }
                    //区域
                    if(requestDto.getAreaId() != null){
                        //所在地区
                        Predicate areaCondition = cb.equal(root.get("areaId") ,requestDto.getAreaId());
                        conditions.add(areaCondition);
                    }
                    //名称
                    if(!StringUtils.isEmpty(requestDto.getUsername())){
                        //单位名称
                        Predicate nameCondition = cb.like(root.get("username") , "%"+requestDto.getUsername()+"%");
                        conditions.add(nameCondition);
                    }
                    if(requestDto.getAdminTypeEnum() != null){
                        //机构　还是　学校
                        Predicate adminTypeEnum = cb.equal(root.get("adminTypeEnum") , requestDto.getAdminTypeEnum());
                        conditions.add(adminTypeEnum);
                    }

                    Predicate[] pre = new Predicate[conditions.size()];

                    cq.where(conditions.toArray(pre));
                    return cq.getRestriction();
                }
            } , page);
            for (Admin admin : pagedAdmin) {          	
            	String area = "";
                if (!StringUtils.isEmpty(admin.getProvinceId())) {
                	area += dtAreaUtil.getAreaName(Long.valueOf(admin.getProvinceId()));
				}              
                if (!StringUtils.isEmpty(admin.getCityId())) {
                	if (area.length()>0) {
                		area += "-";
					}
                	area += dtAreaUtil.getAreaName(Long.valueOf(admin.getCityId()));
				}    
                if (!StringUtils.isEmpty(admin.getAreaId())) {
                	if (area.length()>0) {
                		area += "-";
					}
                	area += dtAreaUtil.getAreaName(Long.valueOf(admin.getAreaId()));
				}
                admin.setLocation(area);
			}

            results.setCount(pagedAdmin.getTotalElements());
            results.setData(pagedAdmin.getContent());
        }


        return results;


    }

    /**
     * 获取当前管理员信息
     * @return
     */
    public ResultDto getCurrentAdmin(HttpServletRequest request){
        Admin currentAdmin = adminService.getCurrentAdmin(request);
        return ResultDto.builder().data(currentAdmin).build();
    }

    /**
     * 获取当前管理员信息
     * @return
     */
    @GetMapping("/type")
    public ResultDto adminType(HttpServletRequest request){
        Admin currentAdmin = adminService.getCurrentAdmin(request);
        AdminTypeEnum type = currentAdmin.getAdminTypeEnum();
        return ResultDto.builder().data(type.getCode()).build();
    }
}
